package hu.village.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import hu.village.mapper.UserMapper;
import hu.village.pojo.Account;
import hu.village.pojo.PageBean;
import hu.village.pojo.User;
import hu.village.service.UserService;
import hu.village.utils.MailUtil;
import hu.village.utils.TimeTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Timer;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TimeTask timeTask;
    @Override
    public void sendRegisterEmail(String email) {
        //注册的验证码状态是0
        String state = "0";
        //调用工具类来发送邮件
        Integer verify_code = mailUtil.sendEmail(email,state);
        LocalDateTime time = LocalDateTime.now();
        //调用mapper层的方法把验证码存到数据库
        userMapper.saveVerifyCode(email,verify_code,time,state);
        log.info("发送的邮箱:{},验证码:{}",email,verify_code);

        //定时删除存入数据库的验证码
        timeTask.setEmail(email);
        timeTask.setState(state);
        Timer timer = new Timer();
        timer.schedule(timeTask,5 * 1000L);
    }

    @Override
    public String Register(User user) {
        //注册的类型码是"0"
        String state = "0";
        String codeSent = userMapper.getCodeByEmailAndState(user.getEmail(),state);
        String codeFilled = user.getVerifyCode();

        if (codeSent.equals(codeFilled)){
            userMapper.insertUser(user);
            return "注册成功";
        }else{
            return "验证码有误";
        }


    }

    @Override
    public User login(User user) {
        return userMapper.selectUser(user);

    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public PageBean selectAccount(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);

        //审核通过的状态是2
        Integer state = 2;
        List<Account> accountList = userMapper.selectAccountByState(state);
        Page<Account> p =  (Page<Account>) accountList;
        PageBean pageBean = new PageBean(p.getTotal(),p.getResult());
        return pageBean;

    }

    @Override
    public void reportAccount(String reportMan,Integer id) {
        //举报审核中的状态是1
        Integer reported = 1;
        userMapper.updateAccountState(reportMan,reported,id);
    }

    @Override
    public Integer selectReportAccount(Account account) {
        return userMapper.getAccountByReportMan(account);
    }

    @Override
    public void repelReport(Account account) {
        userMapper.repelAccount(account);
    }

    @Override
    public void selectHistoryAccount(User user) {
        //审核的状态是1
        user.setStatus(1);
        userMapper.updateUserStatusById(user);
    }
}
